/**
 *@auther: tang
 *@Date: 2021-02-03
 *Project: p2pPlatformSys
 *Lang: TypeScript
 */
import { Service } from 'egg';
import * as utils from '../utils/utils';
const { Op } = require('sequelize');

class bidsService extends Service {
  async add(params:any) {
    // return allBits;
    const { ctx } = this;
    params.num = params.num || utils.getDateNumber();
    const oriData: any = utils.clearObj((await ctx.model.Loan.findAll({ limit: 1 }))[0].dataValues);
    const res:object[] = await ctx.model.Loan.create(utils.generateObjArr(params, oriData));
    return res;
  }
  async update(params:any) {
    const { ctx } = this;
    const bid = params.id;
    const oriData:any = utils.clearNullItems(params);
    console.log(oriData);
    const res:object[] = await ctx.model.Loan.update({ ...oriData }, {
      where: {
        id: bid,
      },
    }).catch(err => {
      console.log(err);
    });
    console.log(res);
    return res;
  }
  async query(params:any) {
    const { ctx } = this;
    const page = params.page || 1,
      size = params.size || 10;
    // const oriData:any = utils.clearNullItems(params);
    // 根据传入的关键字生成查询数组
    const genQuery = utils.generateQueryArr(utils.clearNullItems(params.keywords));
    const queryObj = {
      [Op.and]: [
        genQuery,
        {
          state: {
            [Op.or]: String(params.state).split(','),
          },
        },
      ],

    };
    // 创建外键关联
    const Tbpurpose = ctx.model.Tbpurpose;
    const Loan = ctx.model.Loan;
    Loan.belongsTo(Tbpurpose, { foreignKey: 'purpose' });
    Loan.belongsTo(ctx.model.Tbgrade, { foreignKey: 'grade' });
    Loan.belongsTo(ctx.model.Tbguarantee, { foreignKey: 'guarantee' });
    Loan.belongsTo(ctx.model.Tbrepayment, { foreignKey: 'repayment' });
    Loan.belongsTo(ctx.model.Tbtype, { foreignKey: 'type' });
    Loan.belongsTo(ctx.model.Tbstate, { foreignKey: 'state' });
    Loan.belongsTo(ctx.model.Tbpledge, { foreignKey: 'pledge' });
    const res: object = await ctx.model.Loan.findAll({
      where: queryObj,
      include: [
        { model: Tbpurpose, attributes: [ 'pname' ] },
        { model: ctx.model.Tbgrade, attributes: [ 'gradename' ] },
        { model: ctx.model.Tbguarantee, attributes: [ 'gname' ] },
        { model: ctx.model.Tbrepayment, attributes: [ 'rname' ] },
        { model: ctx.model.Tbtype, attributes: [ 'tname' ] },
        { model: ctx.model.Tbstate, attributes: [ 'id', 'sname' ] },
        { model: ctx.model.Tbpledge, attributes: [ 'pname' ] },
      ],
      limit: Number(size),
      offset: (page - 1) * size,
    }).catch(err => {
      console.log(err);
    });
    const count:object = await ctx.model.Loan.findAll({
      where: queryObj,
    });
    return {
      res,
      count,
    };
  }
}
module.exports = bidsService;
